package com.youlai.boot.modules.policy.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.modules.policy.converter.PolicyConverter;
import com.youlai.boot.modules.policy.mapper.PolicyMapper;
import com.youlai.boot.modules.policy.model.Policy;
import com.youlai.boot.modules.policy.model.PolicyDetailVO;
import com.youlai.boot.modules.policy.model.PolicyForm;
import com.youlai.boot.modules.policy.model.PolicyVO;
import com.youlai.boot.modules.policy.model.PolicyPageQuery;
import com.youlai.boot.modules.policy.service.PolicyService;
import com.youlai.boot.modules.resource.mapper.ResourceMapper;
import com.youlai.boot.modules.resource.model.ResourceVO;

import lombok.RequiredArgsConstructor;

import java.util.List;

import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class PolicyServiceImpl extends ServiceImpl<PolicyMapper, Policy> implements PolicyService {

    private final PolicyConverter policyConverter;
    private final ResourceMapper resourceMapper;

    @Override
    public Page<PolicyVO> getPolicyPage(PolicyPageQuery query) {
        Page<PolicyVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        return baseMapper.getPolicyPage(page, query);
    }

    @Override
    public PolicyDetailVO getPolicyById(Long id) {
        PolicyDetailVO policyDetail = policyConverter.toDetailVo(this.getById(id));

        if (policyDetail != null) {
            List<ResourceVO> images = resourceMapper.getPolicyImages(id);
            policyDetail.setImages(images);            
        }
        return policyDetail;
    }

    @Override
    public Long savePolicy(PolicyForm form) {
        Policy policy = policyConverter.toEntity(form);
        this.save(policy);
        return policy.getId();
    }

    @Override
    public void updatePolicy(PolicyForm form) {
        Policy policy = policyConverter.toEntity(form);
        this.updateById(policy);
    }

    @Override
    public boolean deletePolicy(Long id) {
        return this.removeById(id);
    }
}